﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HTTT.AD;
using System.Configuration;
using HTTT.DTO;
using HTTT.Bussiness;
using HTTT.Utilities;
using HTTT.DataAccess;
using System.Web.Security;


namespace HTTT.admin
{
    public partial class AddUser : System.Web.UI.Page
    {
        /// <summary>
        ///  View State AddItemID
        /// </summary>
        /// 
        private Guid? AddItemID
        {
            get
            {
                object obj = this.ViewState["_AddItemID"];
                if (obj == null)
                    return null; //default to show ID : 0 
                else
                    return (Guid)obj;
            }
            set
            {
                this.ViewState["_AddItemID"] = value;
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
                CheckPermission();
            }
        }

        private void LoadData()
        {
            //Get OU list
            HT_OUBO Bo = new HT_OUBO();
            List<HT_OU> ListBO = Bo.GetAllHT_OU().ToList();
            ddlOU.DataSource = ListBO;
            ddlOU.DataValueField = ADOUProperties.DISTINGUISHEDNAME;
            ddlOU.DataTextField = ADOUProperties.NAME;
            ddlOU.DataBind();
            ddlOU.Items.Insert(0, new ListItem("▼ " + ConfigurationManager.AppSettings["LDAPDomain"], ConfigurationManager.AppSettings["LDAPPath"]));
            ddlOU.SelectedValue = "";
        }

        private void CheckPermission()
        {
            if (!Page.User.IsInRole(Constants.ROLE_SUPER_ADMINISTRATOR)
                 && !Page.User.IsInRole(Constants.ROLE_ADMINISTRATOR))
            {
                Response.Redirect("/admin/AccessDenied.aspx");
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                SaveForm();
                //TODO: Show msg
                Response.Redirect("RequestList.aspx" + AddItemID);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }


        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                bool result = SaveForm();
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatMsgThenRedirect("Tạo yêu cầu thêm mới tài khoản thành công", "UserList.aspx"), true);
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatAlertMsg("Có lỗi xảy ra"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnSaveNew_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                SaveForm();
                AddItemID = null;
                Response.Redirect("AddUser.aspx");
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx");
        }

        private ReturnValue<bool> ValidateData()
        {
	        if (txtFromRequest.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập thông tin yêu cầu");
            if (txtgivenName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Họ người dùng");
            if (txtsurName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Tên người dùng");
            if (txtUserName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Tên người dùng");
            if (ddlOU.SelectedIndex == 0) return new ReturnValue<bool>(false, "Phải chọn OU");

	        return new ReturnValue<bool>(true, "");
        }

        
        private bool SaveForm()
        {
            //Collec infomation
            HT_Request NewRequest = new HT_Request();
            HT_UserBO userBO = new HT_UserBO();
            NewRequest.ID = Guid.NewGuid();
            NewRequest.Action = HT_ACTION.ADD_USER.ToString();
            String distigutedName = "CN=" + txtDisplayName.Text.Trim() + ",";
            distigutedName += ddlOU.SelectedValue;
            long AccountOptions = 512;
            foreach (ListItem i in chklAccountOptions.Items)
            { 
                if(i.Selected)
                {
                    AccountOptions += Convert.ToInt64(i.Value);
                }
            }
            NewRequest.ActionDescription = userBO.BuildAddUserString(
                                        txtgivenName.Text
                                        , txtmidleName.Text
                                        , txtsurName.Text
                                        , txtDisplayName.Text
                                        , txtDescription.Text
                                        , txtMail.Text
                                        , txtHomePage.Text
                                        , txtJob.Text
                                        , txtPhysicalDeliveryOfficeName.Text
                                        , txtCompany.Text
                                        , txtDepartment.Text
                                        , null  //manager
                                        , txtAddress1.Text
                                        , txtAddress2.Text
                                        , txtCity.Text
                                        , txtPostalcode.Text
                                        , txtProvince.Text
                                        , txtCountry.Text
                                        , txtHomephone.Text
                                        , txtOfficephone.Text
                                        , txtMobile.Text
                                        , txtFax.Text
                                        , txtIpphone.Text
                                        , txtNote.Text
                                        , txtUserName.Text
                                        , txtUserName.Text + "@" + ConfigurationManager.AppSettings["LDAPDomain"]
                                        , distigutedName
                                        , AccountOptions
                                        , DateTime.Now
                                        , null
                                        , DateTime.Now
                                        , DateTime.Now);
            string OUName = ddlOU.SelectedItem.Text;
            OUName = OUName.Substring(OUName.IndexOf("├ ") + 1);
            NewRequest.ActionName = "Thêm mới tài khoản <strong>" + txtUserName.Text + "</strong> tại OU <strong>" + OUName + "</strong>" ;
            NewRequest.Note = txtFromRequest.Text;
            NewRequest.Status = Utilities.HT_REQUESTSTATUS.PEDDING.ToString(); 
            NewRequest.RequestDate = DateTime.Now;
            NewRequest.Requestedby = Page.User.Identity.Name;
            HT_RequestBO re = new HT_RequestBO();
            bool result = re.InsertRequest(NewRequest);
            return result;
        }
    }
}